<script setup>
import _ from 'lodash'
import {ref, reactive, computed, watch, onMounted} from 'vue'
import DataTreeNodeSelect from './ele/data-tree-node-select.vue'
import {DFT_ICONS} from "@jzl/icons";
import {$WinForms} from "@jzl/comps";
import {api} from "@jzl/api";

// 定义 props
const props = defineProps({
  action: {
    type: String,
    default: 'view'
  },
  form: {
    type: Object,
    required: true
  },
  mbList: {
    type: Array,
    default: () => []
  },
  apiMap: {
    type: Object,
    default: () => ({})
  },
  mbMap: {
    type: Object,
    default: () => ({})
  },
  dialog: {
    type: Boolean,
    default: false
  },
  isItem: {
    type: Boolean,
    default: false
  },
  triggerPageType: {
    type: String,
    default: null
  },
  page: {
    type: Object,
    default: null
  }
})

// 定义 emits
const emit = defineEmits(['save', 'cancel', 'showCreate', 'showUpdate'])

// 状态
const {
  mbProps,
  json
} = reactive({
  mbProps: {
    label: 'name',
    value: 'code',
    children: 'subs'
  },
  json: null
})

// 计算属性
const actionName = computed(() => {
  switch (props.action) {
    case 'update':
      return '修改变量'
    case 'create':
      return '创建变量'
    default:
      return '查看变量'
  }
})

const isView = computed(() => props.action === 'view')
const isUpdate = computed(() => props.action === 'update')

const pageVars = computed(() => {
  return props.isItem ? _.get(props.page, 'vars') : props.vars
})

const itemVars = computed(() => {
  return props.isItem ? props.vars : []
})

// 方法实现
const isDisableType = (type) => {
  const iTypes = _.get(props.form, 'iTypes')
  return _.isArray(iTypes) && iTypes.length && _.indexOf(iTypes, type) < 0
}

const initVarEnable = (type) => {
  if (type === 'static') {
    setVarEnable('default', null)
  } else if (type === 'api') {
    setVarEnable('formCode', null)
    setVarEnable('viewCode', null)
    setVarEnable('initPath', null)
    setVarEnable('apiFilter', {})
  } else if (type === 'report') {
    setVarEnable('reportId', null)
    setVarEnable('reportCode', null)
  } else if (type === 'mapi') {
    setVarEnable('api', null)
    setVarEnable('initPath', null)
    setVarEnable('mapiFilter', {})
  } else if (type === 'mb') {
    setVarEnable('mbCode', null)
  } else if (type === 'query') {
    setVarEnable('initPath', null)
  } else if (type === 'iQuery') {
    setVarEnable('reportId', null)
    setVarEnable('reportCode', null)
  } else if (type === 'var') {
    setVarEnable('varName', null)
  }
}

const setVarEnable = (prop, value = null) => {
  if (_.isUndefined(props.form[prop])) {
    props.form[prop] = value
  }
}

const getApiLabel = () => {
  const initType = _.get(props.form, 'initType')

  if (initType === 'report') {
    const reportId = _.get(props.form, 'reportId')
    const reportCode = _.get(props.form, 'reportCode')
    const key = `_$report_${reportCode}`
    const report = _.get(props.apiMap, key)
    let label = _.get(report, 'title') || ''

    if (reportCode && !label) {
      label = reportCode
    } else if (reportCode) {
      label += `（${reportCode}）`
    }

    return label
  } else {
    const formCode = _.get(props.form, 'formCode')
    const viewCode = _.get(props.form, 'viewCode')

    if (!formCode) return ''

    const key = formCode + (viewCode ? `$${viewCode}` : '')
    const form = _.get(props.apiMap, key)

    if (!form) return ''

    let label = form.form_name || ''

    if (form.view_name) {
      label += `<JIcon class="el-icon-arrow-left"></JIcon>${form.view_name}<i class="el-icon-arrow-right"></i>`
    }

    return label
  }
}

const handleShowCreate = () => {
  emit('showCreate')
}

const handleShowUpdate = () => {
  emit('showUpdate')
}

const handleSave = () => {
  emit('save')
}

const handleCancel = () => {
  emit('cancel')
}

const showSourceWin = async () => {
  // 这里需要根据你的实际实现来完成
  $WinForms({
    type: 'view',
    onConfirm: async (info) => {
      const form = _.get(info, 'form')
      const view = _.get(info, 'view')

      if (!form || !form.form_id) return

      const formCode = _.get(form, 'form_code', null)
      const formViewCode = _.get(view, 'form_view_code', null)

      props.form.formCode = formCode
      props.form.viewCode = formViewCode

      const fullForm = await api.form.getFormByCode(formCode, formViewCode)
      const key = `${formCode}${formViewCode ? `$${formViewCode}` : ''}`

      props.apiMap[key] = fullForm
    },
  })
}

const showReportWin = async () => {
  // 这里需要根据你的实际实现来完成
  try {
    const report = await $WinReports()

    if (!report || !report.reportdef_id) return

    const id = _.get(report, 'reportdef_id')
    const code = _.get(report, 'reportdef_code')

    props.form.reportId = id
    props.form.reportCode = code

    const key = `_$report_${code}`
    props.apiMap[key] = report
  } catch (error) {
    console.error('Error selecting report:', error)
  }
}

const showApiWin = async () => {
  // 这里需要根据你的实际实现来完成
  try {
    const apiInfo = await $WinMicrosvc()
    const apiUrl = _.get(apiInfo, 'apiUrl')

    if (!apiInfo || !apiUrl) return

    props.form.api = apiUrl
  } catch (error) {
    console.error('Error selecting API:', error)
  }
}

// 生命周期钩子
onMounted(() => {
  const initType = _.get(props.form, 'initType')
  initVarEnable(initType)
})

// Watchers
watch(
  () => props.form.initType,
  (val) => {
    initVarEnable(val)
  }
)
</script>

<template>
  <div class="wd-vars-info">
    <div
      v-if="!dialog"
      class="wd-vars-info-header mr-0 border-t-0 border-left-0 border-r-0"
    >
      <span v-text="actionName" class="flex-1"></span>
      <template v-if="action === 'update' || action === 'create'">
        <el-button type="primary" @click="handleSave">保存</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </template>
      <template v-else-if="action === 'create'">
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
      <template v-else>
        <el-button v-if="form?.prop" type="primary" @click="handleShowUpdate">修改</el-button>
        <el-button v-else @click="handleShowCreate">新增</el-button>
      </template>
    </div>
    <div class="wd-vars-info-cnt">
      <el-form
        size="mini"
        label-position="top"
      >
        <el-form-item
          label="变量名/类型">
          <template #label>
            <div class="wd-vars-form-label">变量名 / 类型</div>
          </template>
          <div class="flex justify-between">
            <el-input
              placeholder="变量属性名，全英文"
              name="prop"
              required
              v-model="form.prop"
              class="flex-1 mr-2"
              :disabled="isView || isUpdate"
            />
            <el-radio-group
              v-model="form.type"
              :disabled="isView || (form.type && form.fixType)"><!--  class="radio-round" -->
              <!--<el-radio-button label="Object" style="width: 58px;">Object</el-radio-button>-->
              <!--<el-radio-button label="Array" style="width: 58px;">Array</el-radio-button>-->
              <el-radio-button label="string">string</el-radio-button>
              <el-radio-button label="number">number</el-radio-button>
              <el-radio-button label="json">json</el-radio-button>
              <el-radio-button label="table">table</el-radio-button>
            </el-radio-group>
          </div>
        </el-form-item>
        <el-form-item label="变量描述">
          <template #label>
            <div class="wd-vars-form-label">变量描述</div>
          </template>
          <el-input placeholder="变量描述" v-model="form.label"></el-input>
        </el-form-item>
        <hr class="mb-2" />
        <el-form-item label="变量值" class="mb-1">
          <template #label>
            <div class="wd-vars-form-label">变量值</div>
          </template>
          <el-radio-group v-model="form.initType" :disabled="isView">
            <el-radio-button label="static" border :disabled="isDisableType('static')">
              <div class="wd-vars-initType">
                <JIcon :icon="DFT_ICONS.varConst" class="wd-vars-item-icon static"></JIcon>
                静态值
              </div>
            </el-radio-button>
            <el-radio-button label="api" border :disabled="isDisableType('api')">
              <div class="wd-vars-initType">
                <JIcon :icon="DFT_ICONS.database" class="wd-vars-item-icon api"></JIcon>
                数据
              </div>
            </el-radio-button>
            <el-radio-button label="mapi" border :disabled="isDisableType('mapi')">
              <div class="wd-vars-initType">
                <JIcon :icon="DFT_ICONS.api" class="wd-vars-item-icon mapi" />
                微接口
              </div>
            </el-radio-button>
            <el-radio-button label="report" border :disabled="isDisableType('report')">
              <div class="wd-vars-initType">
                <JIcon :icon="DFT_ICONS.chartBar" class="wd-vars-item-icon api"></JIcon>
                报表
              </div>
            </el-radio-button>
            <el-radio-button label="mb" border :disabled="isDisableType('mb')">
              <div class="wd-vars-initType">
                <JIcon :icon="DFT_ICONS.mb" class="wd-vars-item-icon mb"></JIcon>
                码表
              </div>
            </el-radio-button>
            <el-radio-button label="query" border :disabled="isDisableType('query')">
              <div class="wd-vars-initType">
                <JIcon :icon="DFT_ICONS.varQuery" class="wd-vars-item-icon option"></JIcon>
                页面入参
              </div>
            </el-radio-button>
            <el-radio-button v-if="isItem" label="iQuery" border :disabled="isDisableType('iQuery')">
              <div class="wd-vars-initType">
                <JIcon
                  :icon="DFT_ICONS.varQuery"
                  class="wd-vars-item-icon query"
                />
                组件入参
              </div>
            </el-radio-button>
            <el-radio-button
              v-if="isItem"
              label="var"
              border
              :disabled="isDisableType('var')"
            >
              <div class="wd-vars-initType">
                <JIcon :icon="DFT_ICONS.var" class="wd-vars-item-icon var" />
                页面变量绑定
              </div>
            </el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          v-if="form.initType === 'mapi' || form.initType === 'api'">
          <div class="w-full">
            <div class="wd-vars-api-info">
              <!--<div slot="label" class="wd-vars-form-label">微接口</div>-->
              <template v-if="form.initType === 'mapi'">
                <el-tag v-if="form.api" size="large" class="mr-2">
                  {{ form.api }}
                </el-tag>
                <el-button type="primary" plain @click="showApiWin()">选择微接口</el-button>
              </template>
              <template v-else>
                <el-tag v-if="form.formCode" size="large" class="mr-2">
                  <div v-html="getApiLabel(form)"></div>
                </el-tag>
                <el-button type="primary" plain @click="showSourceWin()">选择表单数据</el-button>
              </template>
            </div>
            <LinkQuery
              v-if="form.initType === 'mapi'"
              v-model="form.mapiFilter"
              :is-view="action === 'view'"
              :vars="pageVars"
              :ivars="itemVars"
              :trigger-page-type="triggerPageType"
            />
            <LinkQuery
              v-else
              v-model="form.apiFilter"
              :is-view="action === 'view'"
              :vars="pageVars"
              :ivars="itemVars"
              :trigger-page-type="triggerPageType"
            />
          </div>
        </el-form-item>
        <el-form-item v-else-if="form.initType === 'report'">
          <div class="wd-vars-api-info">
            <el-tag v-if="form.reportCode" size="medium" class="mr-1">
              <div v-html="getApiLabel()"></div>
            </el-tag>
            <el-button type="primary" plain @click="showReportWin()">选择报表</el-button>
          </div>
        </el-form-item>
        <template v-else-if="form.initType === 'mb'">
          <el-form-item label="码表数据">
            <div slot="label" class="wd-vars-form-label">码表数据</div>
            <el-cascader
              v-model="form.mbCode"
              placeholder="名称搜索"
              :options="mbList"
              :props="mbProps"
              :disabled="isView"
              filterable></el-cascader>
          </el-form-item>
        </template>
        <template v-else-if="form.initType === 'query'">
          <el-form-item label="页面变量">
            <div slot="label" class="wd-vars-form-label">页面入参名</div>
            <el-input v-model="form.initPath" placeholder="页面入参名"></el-input>
          </el-form-item>
        </template>
        <template v-else-if="form.initType === 'var'">
          <data-tree-node-select
            v-model="form.varName"
            :item="item"
            :page="page"
            nv-type="var"
            v-bind="$attrs"
            placeholder="绑定页面变量"
          />
        </template>
        <!--<template v-else-if="form.initType === 'option'">
            <el-form-item label="表数据">
                <div slot="label" class="wd-vars-form-label">表数据</div>
                <el-tag v-if="form.formCode" size="medium" style="margin-right: 10px;">
                    <div v-html="getApiLabel(form)"></div>
                </el-tag>
                <el-button type="primary" plain @click="showFormWin()">选择表单数据</el-button>
            </el-form-item>
            <el-form-item label="">
                <div slot="label" class="wd-vars-form-label">属性数据</div>
                <el-select v-model="form.itemName">
                    <el-option></el-option>
                </el-select>
            </el-form-item>
        </template>-->

        <el-form-item label="取值路径" v-if="form.initType === 'api' || form.initType === 'mapi'">
          <template #label>
            <div class="wd-vars-form-label">取值路径</div>
          </template>
          <el-input v-model="form.initPath" placeholder="取值路径"></el-input>
        </el-form-item>

        <hr class="mb-2"/>
        <el-form-item class="mb-2">
          <template #label>
            <div class="wd-vars-form-label" v-if="form.initType !== 'static'">
              <el-switch v-model="form.emptyDefault" :disabled="isView" active-text="为空使用默认值"></el-switch>
            </div>
          </template>

          <template v-if="form.emptyDefault || form.initType === 'static'">
            <!--<json-editor-vue v-if="form.type === 'json'" v-model="form.defaultJson"></json-editor-vue>-->
            <!--<el-input placeholder="JSON默认值" :disabled="isView"
                      v-model="form.defaultJson" type="textarea"></el-input>-->
            <template v-if="form.type === 'json'">
              <VJsoneditor
                v-if="isView"
                key="dftView"
                v-model="form.defaultJson"
                class="json-editor-mini"
                height="240px"
                :options="{ mode: 'preview', modes: [], mainMenuBar: false, statusBar: false }"
              />
              <VJsoneditor
                v-else
                key="dftModify"
                v-model="form.defaultJson"
                class="json-editor-mini"
                height="240px"
              />
            </template>
            <div v-else-if="form.type === 'table'">
              <xspreadsheet v-model="form.defaultTable" ref="xsheet" style="height: 200px;"></xspreadsheet>
            </div>
            <el-input
              v-else
              placeholder="默认值"
              :disabled="isView"
              v-model="form.default"
            />
          </template>
        </el-form-item>
      </el-form>
    </div>
    <div v-if="dialog" class="text-center p-2">
      <el-button type="primary" @click="handleSave">保存</el-button>
      <el-button @click="handleCancel">取消</el-button>
    </div>
  </div>
</template>
